<?php
namespace Home\Controller;
use Home\Controller\BaseController;
use Think\Verify;
class LoginController extends BaseController{
	public function __construct(){
		parent::__construct();
	}
	/**
	 * 登录
	 */
	public function index(){
		if (IS_POST) {
			$member_name = trim($_POST['member_name']);
			$pwd = trim($_POST['pwd']);
			if($member_name && $pwd)
			{
				$m_info = M('Member')->where('member_name=\''.$member_name.'\'')->find();
				if(is_array($m_info) && !empty($m_info))
				{
					if ($m_info['pwd'] != re_md5($pwd))
					{
						$this->error("登录密码错误！");
						exit;
					}
					session('member_id',$m_info['member_id']);
                    session('member_name',$m_info['member_name']);
					$this->success("登录成功！",U('Index/index'));
					exit;
				}else{
					$this->error("不存在此用户！");
					exit;
				}
			}
		}elseif (IS_GET) {
			$this->check_login();
			$this->display();
		}
	}
	/**
	 * 注册
	 */
	public function register(){
		if (IS_POST) {

			$data = array();
			$data['member_name'] = str_rp(trim($_POST['member_name']));
			$data['email'] = str_rp(trim($_POST['email']));
			$data['pwd'] = re_md5(trim($_POST['pwd']));
			$data['register_time'] = NOW_TIME;
            $data['invite_code'] = str_rp(trim($_POST['invite_code']));
            //后端验证邀请码是否有效
            $msg="";
            if (!empty($data['invite_code'])) {
                $res=M('invite_code')->where(array('invite_code'=>$data['invite_code']))->find();
                if($res && $res['status']!=0){
                    $msg="该邀请码只能使用一次，已经过期";
                }elseif(!$res){
                    $msg="邀请码错误";
                }
            }else{
                $msg="邀请码不能为空";
            }
            if($msg!=""){
                $this->error($msg);
                exit;
            }

			$api = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php';
			$ipparam['format'] = 'js';
			$ipparam['ip'] = get_client_ip();
			$res = get_api($api,$ipparam,'array');
			if (!empty($res['city'])) {
				$data['usercity'] = $res['city'];
			}
			$member_id = M('Member')->add($data);
			if($member_id)
			{
                M('invite_code')->where(array('invite_code'=>$data['invite_code']))->save(array('status'=>1)); // 更新邀请码为已使用状态
				unset($data);
				session('member_id',$member_id);
				$this->success("注册成功！",U('Index/index'));
				exit;
			}
		}elseif (IS_GET){
			$this->check_login();
			$this->display();
		}
	}
	/**
	 * 找回密码
	 */
	public function forgot()
	{
		if(IS_POST)
		{
			$map = array();
			$map['member_name'] = array('eq',trim($_POST['member_name']));
			$map['email'] = array('eq',trim($_POST['email']));
			$f_info = M('Member')->where($map)->find();
			if(is_array($f_info) && !empty($f_info))
			{
				//发邮件
				$mid = encrypt($f_info['member_id']);
				$v_link = C('SiteUrl').'/Public/set_pwd/mcode/'.$mid.'.html';
				//$res = SendMail($f_info['email'], "找回密码", "找回密码验证");
				$res = SendMail($f_info['email'], "找回密码", "找回密码链接为 ".$v_link.' 点击链接重新修改密码！');
				if($res)
				{
					echo"<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/><script>if(confirm('邮件已发送到您的邮箱，打开邮箱找回密码！')){window.location.href='".U('Public/forgot')."'}</script>";
					exit;
				}else{
					$this->error("邮件发送失败，请稍后再试！");
					exit;
				}
			}else{
				//提示错误
				$this->error("您输入的信息不匹配！");
				exit;
			}
		}else{
			$this->display();
		}
	}
	/**
	 * 修改密码
	 */
	public function set_pwd()
	{
		if(IS_GET && trim($_GET['mcode']))
		{
			$mcode = trim($_GET['mcode']);
			$mid = decrypt($mcode);
			$map = array();
			$map['member_id'] = array('eq',intval($mid));
			$f_info = M('Member')->where($map)->find();
			if(is_array($f_info) && !empty($f_info))
			{
				$this->assign('f_info',$f_info);
				$this->display();
			}else{
				$this->error("非法请求！");
				exit;
			}
		}
		if(IS_POST)
		{
			$member_id = intval($_POST['member_id']);
			$pwd = re_md5(trim($_POST['pwd']));
			$rst = M('Member')->where('member_id='.$member_id)->setField('pwd',$pwd);
			if($rst)
			{
				$this->success("密码修改成功！",U('login'));
				exit;
			}else{
				$this->error("操作失败！");
				exit;
			}
		}
	}
	/**
	 * 生成验证码
	 */
	public function get_verify(){
		$config = array(
				'length' => 4,
				'fontSize' => 14,
				'imageW' => 95,
				'imageH' => 30,
				'useNoise' => false,
				'useCurve' => false,
		);
		$verify = new Verify($config);
		$verify->entry();
	}
	/**
	 * 验证验证码
	 * @param string $code 验证码
	 * @param string $id 标示id
	 * @return boolean
	 */
	function check_verify($code, $id = ''){
		$verify = new \Think\Verify();
		if (!empty($_GET['captcha'])) {
			$code = $_GET['captcha'];
			$res =  $verify->check($code);
			$data = json_encode($res);
			echo $data;
		}
		return $verify->check($code, $id);
	}

    /**
     * 验证邀请码
     * @param string $code 验证码
     * @param string $id 标示id
     * @return boolean
     */
    function check_invite_code(){
        if (!empty($_GET['invite_code'])) {
            $code = $_GET['invite_code'];
            $res=M('invite_code')->where(array('invite_code'=>$code))->find();
            $msg=true;
            if($res && $res['status']!=0 || !$res){
                $msg=false;
            }
            $data = json_encode($msg);
            echo $data;exit;
        }
        return false;
//        echo json_encode(false);exit;
    }
	/**
	 * 验证用户名
	 */
	public function check_member(){
		$member_name = trim($_GET['member_name']);
		if($member_name != '')
		{
			$num = M('Member')->where('member_name=\''.$member_name.'\'')->count();
			if($num>0)echo 'false'; else echo 'true';
		}else{
			echo 'false';
		}
	}
	/**
	 * 验证电话号码
	 */
	public function check_phone(){
		$mobile = trim($_GET['mobile']);
		if($mobile != '') {
			$num = M('Member')->where('mobile=\''.$mobile.'\'')->count();
			if($num>0)echo 'false'; else echo 'true'; 	   
		}else{
			echo 'false'; 
		}
	}
	/**
	 * 验证邮箱
	 */
	public function check_email()
	{
		$email = trim($_GET['email']);
		if($email)
		{
			$num = M('Member')->where('email=\''.$email.'\'')->count();
			if($num>0)echo 'false'; else echo 'true';
		}
	}
}